package pps.et5.eit.ex2;

import java.util.Scanner;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;

import pps.et5.eit.ex1.Producer;

public class Service implements MessageListener {
	private ConnectionFactory connectionFactory; 
	private Destination request;
	private Destination response;
	private static Connection connection;
	private MessageConsumer consumer;
	private MessageProducer producer;
	private Session session;
	public static void main(String[] args) {
		try {
			Service service = new Service();
			service.connect();
			service.init();
			System.out.println("Waiting for messages ...");
			try {
				Thread.sleep(30000);
			}
			catch (java.lang.InterruptedException ie) {
				ie.printStackTrace(System.err);
			}
		} catch (Throwable t) {
			t.printStackTrace();
		} finally {
			try {
				connection.close();
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void init() throws Exception {

		// Créer une connexion au système de messagerie
		// Et affiche les messages au fur et à mesure de leur arrivée dans la queue
		// Création d'une Connexion et d'une Session

		// Réception des messages jusqu’à obtention d’un message non texte 
		connection = connectionFactory.createConnection();
		session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		// Création d'un MessageConsumer et d'un message producer

		consumer = session.createConsumer(request);
		producer = session.createProducer(response);
		consumer.setMessageListener(this);
		connection.start();
		// Fermeture de la connexion

	}
	private void connect() throws Exception {
		// Initialise les attributs connectionFactory et destination.
		// Création d'un contexte JNDI
		InitialContext jndiContext = new InitialContext();
		// Lookup de la fabrique de connexion et de la destination
		connectionFactory = (ConnectionFactory) jndiContext.lookup("connectionFactory"); 
		request = (Destination) jndiContext.lookup("Request");
		response = (Destination) jndiContext.lookup("Response");

	}
	@Override
	public void onMessage(Message m) {
		StringBuffer rev;
		if (m instanceof TextMessage) {
			try {
				rev = new StringBuffer(((TextMessage) m).getText());
				System.out.println("Message reçu: "+rev.toString());
				rev.reverse();
				TextMessage message = session.createTextMessage(rev.toString());
				// Envoi d'un message
				System.out.println("Message envoyé: "+rev.toString());
				producer.send(message);
				
			} catch (JMSException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}


	}
}
